package cxm.proj.xtalk;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import cxm.lib.util.MyLog;
import cxm.proj.xtalk.smack.ConnectManager;
import cxm.proj.xtalk.smack.UserManager;

public class LoginActivity extends Activity {
	private EditText userText = null;
	private EditText passText = null;
	private Button loginButton = null;
	// private Button settingButton = null;
	// private ProgressBar progressBar = null;
	private SharedPreferences prefs = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		
		this.userText = (EditText)this.findViewById(R.id.edit_username);
		this.passText = (EditText)this.findViewById(R.id.edit_password);
		this.loginButton = (Button)this.findViewById(R.id.btn_login);
		// this.progressBar = (ProgressBar)this.findViewById(R.id.progressBar);
		// this.settingButton = (Button)this.findViewById(R.id.btn_setting);
		
		// get shread preference
		this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
		this.userText.setText(this.prefs.getString("user", ""));
		this.passText.setText(this.prefs.getString("pass", ""));
		
		// if we already login, start buddy list directly
		if (UserManager.getInstance().hasUser() &&
				UserManager.getInstance().getUser().isLogin()) {
			// login, go to buddy page
			final Intent mainIntent = new Intent(LoginActivity.this,
					MainActivity.class);
			LoginActivity.this.startActivity(mainIntent);
			LoginActivity.this.finish();
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		
		// if login fail, not triger login action
		Bundle bundle = this.getIntent().getExtras();
		if (null != bundle && bundle.getString("type", "").equals("LoginFail"))
			return;

		// fake login clicked
		String user = this.userText.getText().toString();
		String pass = this.passText.getText().toString();
		if (user.length() != 0 && pass.length() != 0)
			this.loginButton.performClick();
	}
	
	public void onLoginClicked(View view) {
		// get view
		// Button button = (Button)view;
		String username = userText.getText().toString();
		String password = passText.getText().toString();
		if (username.length() == 0 || password.length() == 0) {
			this.showWarning(this.getString(R.string.error_user));
			return;
		}
		
		// check is login
		if (UserManager.getInstance().hasUser() &&
				UserManager.getInstance().getUser().isLogin()) {
			MyLog.Log(MyLog.Level.Warning, "Already login");
			return;
		}
		
		// set ConnectManager
		String serverip = this.prefs.getString("prefs_serverip", "");
		String servername = this.prefs.getString("prefs_servername", "");
		if (serverip.length() == 0 || servername.length() == 0) {
			this.showWarning(this.getString(R.string.error_server));
			return;
		}

		ConnectManager.getInstance().createConnector(serverip, servername);
		// create user account
		UserManager.getInstance().setLoginAccount(username, password);
		
		// go to main activity directly
		final Intent mainIntent = new Intent(LoginActivity.this,
				MainActivity.class);
		LoginActivity.this.startActivity(mainIntent);
		LoginActivity.this.finish();
		
		/*
		// after connect, we try to login
		try {
			UserManager.getInstance().login(new ConnectTaskResultHandle() {
				@Override
				public void taskResultHandle(int result, Object tag) {
					if (0 == result) {
						MyLog.Log(MyLog.Level.Info, "User login success");
						// save login account
						prefs.edit().putString("user", userText.getText().toString()).commit();
						prefs.edit().putString("pass", passText.getText().toString()).commit();
						
						// login, go to buddy page
						final Intent mainIntent = new Intent(LoginActivity.this,
								MainActivity.class);
						LoginActivity.this.startActivity(mainIntent);
						LoginActivity.this.finish();
					} else {
						MyLog.Log(MyLog.Level.Error, "Cannot login: " + result);
						Toast.makeText(MyApplication.context, 
								"Cannot login: " + result, Toast.LENGTH_LONG).show();
						
						// reset state
						setLoginUI(false);
						UserManager.getInstance().Release();
						ConnectManager.getInstance().Release();
					}
				}
			}, button);

			// set hide view
			this.setLoginUI(true);
		} catch (Exception e) {
			MyLog.Log(MyLog.Level.Error, "Cannot login: " + e);
		}
		*/
	}
	
	/*
	private void setLoginUI(boolean isLogin) {
		this.progressBar.setVisibility(isLogin ? View.VISIBLE : View.INVISIBLE);
		this.loginButton.setVisibility(isLogin ? View.INVISIBLE: View.VISIBLE);
		this.userText.setVisibility(isLogin ? View.INVISIBLE : View.VISIBLE);
		this.passText.setVisibility(isLogin ? View.INVISIBLE : View.VISIBLE);
		this.settingButton.setVisibility(isLogin ? View.INVISIBLE : View.VISIBLE);
	}
	*/
	
	public void onAdvanceSettingClick(View view) {
		// start setting intent
		Intent intent = new Intent(this, SettingActivity.class);
		startActivity(intent);
	}
	
	private void showWarning(String warning) {
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		dialogBuilder.setTitle(this.getString(R.string.error_title));
		dialogBuilder.setMessage(warning);
		dialogBuilder.setPositiveButton(this.getString(R.string.error_yes),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						arg0.cancel();
					}
				});
		AlertDialog dialog = dialogBuilder.create();
		dialog.show();
	}
}
